<template>
    <div>
        <div class="e-table" style="background-color: #fff">
            <!-- 头部buttons -->
            <div class="top">
                <div class="left">
                    <div>
                        <!-- @click="openNewPage('tenderList')" -->
                        <el-button size="small" class="btn-greenYellow" @click="importList"
                            >引入清单</el-button
                        >
                        <el-button size="small" class="btn-greenYellow" @click="addBrother"
                            >新增同级</el-button
                        >
                    </div>
                </div>
            </div>
        </div>
        <div style="display: flex">
            <div class="left" style="width: 20%">
                <div class="e-tree-file">
                    <div class="title">包件名称</div>
                    <el-tree
                        :data="detailsOfProposedArr"
                        :props="defaultProps"
                        @node-click="handleNodeClick"
                    ></el-tree>
                </div>
            </div>
            <div class="right" style="flex: 1; position: relative; margin-left: 20px">
                <div class="e-tree-table">
                    <el-table
                        ref="tableRef"
                        border
                        style="width: 100%"
                        row-key="listId"
                        :data="tableData"
                        :tree-props="{
                            children: 'children',
                            hasChildren: 'hasChildren'
                        }"
                        :load="onload"
                        lazy
                        :row-class-name="tableRowClassName"
                    >
                        <el-table-column
                            type="selection"
                            prop="code"
                            label="操作"
                            width="80"
                        ></el-table-column>
                        <el-table-column prop="code" label="操作" width="200" align="left">
                            <template slot-scope="{ row }">
                                <div class="oparation_box">
                                    <img
                                        src="@/assets/btn/sub.png"
                                        class="add_sub"
                                        @click="addChilden(row)"
                                        title="添加子级"
                                    />
                                    <i
                                        class="el-icon-delete"
                                        style="font-size: 24px; color: #e9513e"
                                        @click="onDelNode(row)"
                                        title="删除"
                                    ></i>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="code" label="细目编号" min-width="220">
                            <template slot-scope="{ row }">
                                <el-input
                                    v-model="row.code"
                                    placeholder="请输入内容"
                                    v-if="row.inputState"
                                ></el-input>
                                <span v-else>{{ row.code }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="codeName" label="细目名称" min-width="120">
                            <template slot-scope="{ row }">
                                <el-input
                                    v-model="row.codeName"
                                    placeholder="请输入内容"
                                    v-if="row.inputState"
                                ></el-input>
                                <span v-else>{{ row.codeName }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="subitemName" label="分部分项" width="120">
                            <template slot-scope="{ row }">
                                <el-input
                                    v-model="row.subitemName"
                                    placeholder="请输入内容"
                                    v-if="row.inputState"
                                ></el-input>
                                <span v-else>{{ row.subitemName }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="unit" label="计量单位" width="120">
                            <template slot-scope="{ row }">
                                <el-input
                                    v-model="row.unit"
                                    placeholder="请输入内容"
                                    v-if="row.inputState"
                                ></el-input>
                                <span v-else>{{ row.unit }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="priceType" label="单价类型" width="120">
                            <template slot-scope="{ row }">
                                <el-input
                                    v-model="row.priceType"
                                    placeholder="请输入内容"
                                    v-if="row.inputState"
                                ></el-input>
                                <span v-else>{{ row.priceType }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="num" label="数量" width="120">
                            <template slot-scope="{ row }">
                                <el-input
                                    v-model="row.num"
                                    placeholder="请输入内容"
                                    v-if="row.inputState"
                                    @change="onCalcAmount(row)"
                                ></el-input>
                                <span v-else>{{ row.num }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="price" label="单价" width="120">
                            <template slot-scope="{ row }">
                                <el-input
                                    v-model="row.price"
                                    placeholder="请输入内容"
                                    v-if="row.inputState"
                                    @change="onCalcAmount(row)"
                                ></el-input>
                                <span v-else>{{ row.price }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="amount" label="金额(元)" width="120">
                            <template slot-scope="{ row }">
                                <span>{{ row.amount }}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import applyRequest from '@/api/tender/apply.js'
// import tenderRequest from '@/api/tender/tender.js'
import { toLocation, vueDom } from '@/utils/common.js'
import { uidBuilder } from '@/api/base/uid.js'

export default {
    props: {
        detailsOfProposed: {
            type: Array,
            default: function () {
                return []
            }
        },
        tenderClass: {
            type: String,
            default: ''
        }
    },
    computed: {
        tenderId () {
            return this.$route.query.billid
        }
    },
    data () {
        return {
            detailsOfProposedArr: [],
            tableData: [],
            mapTableData: {},
            addList: [] // 缓存新增数据
        }
    },
    created () {
        this.findByApplyId()
        this.importList()
    },
    mounted () {
        vueDom(
            // 默认0为选中项
            () => {
                $('.el-tree-node:first')?.addClass('is-current')
            },
            () => {
                return $('.el-tree-node:first')?.attr('class')?.includes('is-current')
            }
        )
    },
    methods: {
        // 获取包件列表数据
        async findByApplyId () {
            let data = []
            let leftTree = []
            if (this.detailsOfProposed.length !== 0) {
                data = this.detailsOfProposed
            } else {
                await applyRequest.bidPackageListByBillId(this.tenderId).then(res => {
                    data = res
                })
            }
            data.forEach(value => {
                leftTree.push({ label: value.name })
            })
            this.detailsOfProposedArr = leftTree
        },
        // 通过id获取子级数据
        async getById (listId) {
            // （此处为模拟）
            const uid = await this.uidBuilder({ num: 2 })
            // 右侧树列表假数据
            const result = [
                {
                    recordId: '', //记录ID
                    packageId: '123', //包件ID
                    parentId: listId, //父级ID
                    code: uid[0], //细目编码
                    codeName: '123', //细目名称
                    isLeaf: 0, //是否是最明细级
                    hasChildren: true,
                    listId: uid[0], //本级ID
                    subitemName: '123', //分部分项名称
                    subitemId: '123', //分部分项ID
                    budgetName: '123', //预算名称
                    budgetId: '123', //预算id
                    unit: '123', //计量单位
                    num: 123, //数量 默认值为零
                    price: 123, //单价 默认值为零
                    priceType: '123', //单价类型 (劳务单价 全单价) 工程招标特有
                    amount: 123, //金额
                    billId: this.tenderId, //单据Id
                    label: 0, //标识(0,清单，1项，2结构部位)"
                    changeState: 1 //清单变更状态 0未变更 1新增 2编辑 -1删除
                },
                {
                    recordId: '', //记录ID
                    packageId: '123', //包件ID
                    parentId: listId, //父级ID
                    code: uid[1], //细目编码
                    codeName: '123', //细目名称
                    isLeaf: 0, //是否是最明细级
                    hasChildren: true,
                    listId: uid[1], //本级ID
                    subitemName: '123', //分部分项名称
                    subitemId: '123', //分部分项ID
                    budgetName: '123', //预算名称
                    budgetId: '123', //预算id
                    unit: '123', //计量单位
                    num: 123, //数量 默认值为零
                    price: 123, //单价 默认值为零
                    priceType: '123', //单价类型 (劳务单价 全单价) 工程招标特有
                    amount: 123, //金额
                    billId: this.tenderId, //单据Id
                    label: 0, //标识(0,清单，1项，2结构部位)"
                    changeState: 1 //清单变更状态 0未变更 1新增 2编辑 -1删除
                }
            ]
            return result
        },
        async importList () {
            const result = await this.getById('0')
            this.tableData = result
            this.mapTableData['0'] = {
                children: result
            }
        },
        async onload (row, treeNode, resolve) {
            let result
            // 如果不是最子级，就从接口取
            if (!row.isLeaf) {
                result = await this.getById(row.listId)
            } else {
                // 是最子级，则初始为空，合并新增数据，并设为非最子级
                result = []
                row.isLeaf = 0
            }
            // 如果有缓存数据，说明是点击的 “添加子级” 按钮
            if (this.addList.length > 0) {
                result = result.concat(this.addList)
                this.addList = []
            }
            row.treeNode = treeNode
            row.resolve = resolve
            row.children = result
            this.mapTableData[row.listId] = row
            resolve(result)
        },
        // 添加子级
        async addChilden (row) {
            const { listId } = row
            const uid = await this.uidBuilder({ num: 1 })
            const addData = {
                recordId: '', //记录ID
                packageId: '123', //包件ID
                parentId: listId, //父级ID
                code: uid, //细目编码
                codeName: '123', //细目名称
                isLeaf: 1, //是否是最明细级
                hasChildren: false,
                listId: uid, //本级ID
                subitemName: '123', //分部分项名称
                subitemId: '123', //分部分项ID
                budgetName: '123', //预算名称
                budgetId: '123', //预算id
                unit: '123', //计量单位
                num: 123, //数量 默认值为零
                price: 123, //单价 默认值为零
                priceType: '123', //单价类型 (劳务单价 全单价) 工程招标特有
                amount: 123, //金额
                billId: this.tenderId, //单据Id
                label: 0, //标识(0,清单，1项，2结构部位)"
                changeState: 1, //清单变更状态 0未变更 1新增 2编辑 -1删除
                inputState: true
            }
            const tableRef = this.$refs.tableRef
            console.log(this.mapTableData, this.mapTableData[listId])
            if (!this.mapTableData[listId]) {
                // 缓存新增数据
                this.addList.push(addData)
                // 如果是最子级，则设为目录
                if (!row.hasChildren) {
                    row.children = row.children ? row.children.push(addData) : [addData]
                    row.hasChildren = true
                    this.mapTableData[listId] = row
                    // 切换展开状态
                    this.$nextTick(() => {
                        // tableRef.toggleRowExpansion(row, true)
                        tableRef.store.loadOrToggle(row)
                    })
                    // }
                } else {
                    // 展开子级
                    // tableRef.store.loadData(row, listId)
                    tableRef.store.loadOrToggle(row)
                }
            } else {
                // 已经展开，则直接添加
                row.children.push(addData)
            }
            // 定位到新添加行
            toLocation(addData)
        },
        onDelNode (row) {
            // 如果是新增的，则直接删除
            if (!row.recordId) {
                const siblings = this.mapTableData[row.parentId].children
                const index = siblings.find(item => item.listId === row.listId)
                siblings.splice(index, 1)
            } else {
                // 否则先提示，再删除
                this.clientPop(
                    'err',
                    '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                    () => {
                        const siblings = this.mapTableData[row.parentId].children
                        const index = siblings.find(item => item.listId === row.listId)
                        siblings.splice(index, 1)
                    }
                )
            }
        },
        // 输入后计划金额
        onCalcAmount (row) {
            row.amount = row.num * row.price
            // 向上汇总金额
            this.recurCount({
                parentId: row.parentId,
                rootId: '0',
                listField: 'listId',
                parentField: 'parentId',
                row
            })
        },
        // 递归统计父级
        recurCount ({ parentId, rootId, listField, parentField, row }) {
            const parent = this.mapTableData[parentId]
            // 统计所有同级
            const countSibling = parent.children.reduce((prev, item) => {
                return prev + Math.round(item.amount)
            }, 0)
            // 赋值汇总数据给父级
            parent.amount = countSibling // 赋值汇总数据给父级
            // 到根节点
            if (parentId === rootId) {
                return
            }

            // 未到根节点则继续遍历父节点
            return this.recurCount({
                parentId: parent[parentField],
                rootId,
                listField,
                parentField,
                row
            })
        },
        tableRowClassName ({ row }) {
            return `class-${row.listId}`
        },
        async uidBuilder (params) {
            let temp = ''
            await uidBuilder(params).then(res => {
                temp = res.length === 1 ? res[0] : res
            })
            return temp
        }
        // refreshLoadTree (parentId) {
        //     // 根据父级id取出对应节点数据
        //     // const { row, treeNode, resolve } = this.mapTableData[parentId]
        //     let children = this.mapTableData[parentId].children
        //     const tableRef = this.$refs.tableRef
        //     this.$set(tableRef.store.states.lazyTreeNodeMap, parentId, children)
        // },
    }
}
</script>
<style lang="scss" scoped>
.e-tree-table {
    ::v-deep .el-table {
        .el-table_1_column_2 {
            .cell {
                display: flex;
                align-items: center;
            }
        }
        .el-table__header {
            .el-table_1_column_2 {
                .cell {
                    justify-content: center;
                }
            }
        }
    }
}
</style>
